<?php namespace App\Foundation\Service;

use App\Exceptions\Item\OrderException;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;

class WechatPayService
{
    /**
     * @var Application
     */
    private $app;

    private function __construct($config)
    {
        $options = [
            'app_id'  => $config['app_id'],
            'payment' => [
                'merchant_id' => $config['payment']['merchant_id'],
                'key'         => $config['payment']['key'],
                'cert_path'   => $config['payment']['cert_path'],
                'key_path'    => $config['payment']['key_path'],
            ],
        ];
        $this->app = new Application($options);
    }

    /**
     * @return WechatPayService
     */
    public static function wechatMp()
    {
        $config = config('wechat');
        $gateway = new static($config);

        return $gateway;
    }

    /**
     * 创建预付订单
     *
     * @param Order $order
     *
     * @return string
     */
    public function createPrepayOrder(Order $order)
    {
        $payment = $this->app->payment;
        $result = $payment->prepare($order);

        $local_sign = \EasyWeChat\Payment\generate_sign($result->except('sign')->all(), $payment->getMerchant()->key,
            'md5');
        if ($local_sign == $result->sign && $result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
            return $result->toArray();
        }
        throw new OrderException(OrderException::CREATE_PREPAY_ORDER_FAILURE);
    }

    public function __call($method, $parameters)
    {
        if (method_exists($this->app->payment, $method)) {
            return call_user_func_array([$this->app->payment, $method], $parameters);
        }

        return call_user_func_array([$this->app, $method], $parameters);
    }
}
